package com.zb.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.AccounLoginInfo;
import com.zb.entity.ExportFieldAttrVo;
import com.zb.entity.ExportFieldVo;
import com.zb.entity.ZjNetworkFieldExport;
import com.zb.mapper.ZjNetworkFieldExportMapper;
import com.zb.service.ZjNetworkFieldExportService;
import com.zb.vo.NetworkSysInitExportVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.management.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务商字段导出表 服务实现类
 * </p>
 *
 * @author WEN
 * @since 2024-03-05
 */
@Service
public class ZjNetworkFieldExportServiceImpl extends ServiceImpl<ZjNetworkFieldExportMapper, ZjNetworkFieldExport> implements ZjNetworkFieldExportService {
    @Resource
    private ZjNetworkFieldExportMapper networkFieldExportMapper;

    // 获取服务商初始化系统导出字段
    @Override
    public List<NetworkSysInitExportVo> getNetworkSysInitExportFields() {
        return networkFieldExportMapper.getNetworkSysInitExportFields();
    }

    // 获取所有服务商导出字段
    @Override
    public List<ExportFieldAttrVo> getNetworkExportFields(AccounLoginInfo loginInfo) {
        QueryWrapper<ZjNetworkFieldExport> wrapper = new QueryWrapper<>();
        wrapper.select("field")
                .eq("cust_acc_id", loginInfo.getCustAccId())
                .eq("account_id", loginInfo.getId());
        ZjNetworkFieldExport fieldExport = this.getOne(wrapper);
        if (null == fieldExport || StringUtils.isBlank(fieldExport.getField())) {
            return new ArrayList<>();
        }
        return JSON.parseArray(fieldExport.getField(), ExportFieldAttrVo.class);
    }

    // 保存服务商导出字段
    @Override
    public void save(AccounLoginInfo loginInfo, ExportFieldVo fieldVo) {
        QueryWrapper<ZjNetworkFieldExport> wrapper = new QueryWrapper<>();
        wrapper.select("id")
                .eq("cust_acc_id", loginInfo.getCustAccId())
                .eq("account_id", loginInfo.getId());
        ZjNetworkFieldExport fieldExport = this.getOne(wrapper);
        if (null != fieldExport) {
            fieldExport.setField(JSON.toJSONString(fieldVo.getFieldAttrs()));
            this.updateById(fieldExport);
            return;
        }
        fieldExport = new ZjNetworkFieldExport();
        fieldExport.setId(IdWorker.getId());
        fieldExport.setCustAccId(loginInfo.getCustAccId());
        fieldExport.setAccountId(loginInfo.getId());
        fieldExport.setField(JSON.toJSONString(fieldVo.getFieldAttrs()));
        this.save(fieldExport);
    }
}
